package net.projects.pro5_rss.writer;

import net.projects.pro5_rss.Buffer.NewsBuffer;
import net.projects.pro5_rss.bean.CommonInformationItem;
import net.projects.pro5_rss.dao.ProjectProperties;
import org.apache.log4j.Logger;

import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NewsWriterTask implements Runnable{
    private String name;
    private NewsBuffer buffer;
    private boolean flag;
   static Logger log = Logger.getLogger(NewsWriterTask.class);
    public NewsWriterTask(String name, NewsBuffer buffer) {
        this.name = name;
        this.buffer = buffer;
    }
    public NewsWriterTask( NewsBuffer buffer) {
        this.name = "未知新闻源";
        this.buffer = buffer;
    }


    @Override
    public void run() {
        while (!flag&&!Thread.currentThread().isInterrupted()){
            CommonInformationItem item = null;
            try{
                item = buffer.get();
            }catch (Exception e){
                throw new RuntimeException(e);
            }
            if (item==null){
                System.out.println("无数据写入");
                continue;
            }
            Path p= Paths.get(ProjectProperties.getInstance().getProperty("file.path")+item.getFileName());
            try(BufferedWriter writer= Files.newBufferedWriter(p, StandardOpenOption.CREATE)){
                writer.write(item.toString());
                writer.flush();
            }catch (Exception e){
                log.error(e);
            }
        }
    }
}
